package com.jz.community.basecomm.loaction;

import android.Manifest;
import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.gyf.barlibrary.ImmersionBar;
import com.jz.community.basecomm.base.BaseMvpActivity;
import com.jz.community.basecomm.bean.RegionsBean;
import com.jz.community.basecomm.mvp.BaseMvpPresenter;
import com.jz.community.basecomm.utils.BaseSpUtils;
import com.jz.community.basecomm.utils.RxDataTool;
import com.jz.community.basecomm.utils.SHelper;
import com.jz.community.basecomm.utils.WpToast;
import com.jz.community.basecomm.utils.permission.PermissionUtil;
import com.jz.community.basecommunity.R;
import com.jz.community.basecommunity.R2;
import com.jz.community.commview.view.WaveSideBarView;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class LocActivity extends BaseMvpActivity {


    @BindView(R2.id.loc_rv)
    RecyclerView locRv;
    @BindView(R2.id.loc_side)
    WaveSideBarView locSide;
    @BindView(R2.id.loc_change_back)
    ImageView locChangeBack;
    @BindView(R2.id.loc_change_delete)
    ImageView locChangeDelete;
    @BindView(R2.id.loc_change_edit)
    EditText locChangeEdit;
    @BindView(R2.id.loc_change_rl)
    RelativeLayout locChangeRl;
    @BindView(R2.id.loc_change_toolbar)
    Toolbar locChangeToolbar;
    @BindView(R2.id.loc_change_now_city)
    TextView locChangeNowCity;
    @BindView(R2.id.loc_change_now_city_rl)
    RelativeLayout locChangeNowCityRl;
    @BindView(R2.id.loc_change_loc_city)
    TextView locChangeLocCity;
    @BindView(R2.id.loc_change_loc_city_ll)
    LinearLayout locChangeLocCityLl;
    @BindView(R2.id.loc_change_near_city1)
    TextView locChangeNearCity1;
    @BindView(R2.id.loc_change_near_city2)
    TextView locChangeNearCity2;
    @BindView(R2.id.loc_change_near_city_ll)
    LinearLayout locChangeNearCityLl;

    private LinearLayoutManager linearLayoutManager;
    private CityAdapter adapter_city;

    //最近定位的城市
    private List<RegionsBean.EmbeddedBean.ContentBean> nearCityList;
    private CompositeDisposable compositeDisposable;
    private int isLocSuccess = -1; // 0 成功 1 失败
    private RegionsBean.EmbeddedBean.ContentBean LocContentBean = null;

    @Override
    protected int getContentView() {
        return R.layout.activity_loc_change;
    }

    @Override
    protected BaseMvpPresenter createPresenter() {
        return null;
    }

    @Override
    protected void initView() {
        ImmersionBar
                .with(this)
                .titleBar(locChangeToolbar)
                .statusBarDarkFont(true, 0.2f)
                .init();
        locRv.setHasFixedSize(true);
        locRv.setFocusable(false);
        linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        locRv.setLayoutManager(linearLayoutManager);
        adapter_city = new CityAdapter(R.layout.item_loc_city, new ArrayList<>());
        locRv.setAdapter(adapter_city);
    }

    @Override
    protected void initDatas() {
        nearCityList = getNearCityHistoryList();
        if (null != nearCityList && nearCityList.size() > 0) {
            if (nearCityList.size() == 1) {
                locChangeNearCity1.setVisibility(View.VISIBLE);
                locChangeNearCity2.setVisibility(View.INVISIBLE);
                locChangeNearCity1.setText(nearCityList.get(0).getName());
            } else {
                locChangeNearCity1.setVisibility(View.VISIBLE);
                locChangeNearCity1.setText(nearCityList.get(0).getName());
                locChangeNearCity2.setVisibility(View.VISIBLE);
                locChangeNearCity2.setText(nearCityList.get(1).getName());
            }
        } else {
            locChangeNearCity1.setVisibility(View.INVISIBLE);
            locChangeNearCity2.setVisibility(View.INVISIBLE);
        }
        RegionsBean.EmbeddedBean.ContentBean region = BaseSpUtils.getInstance().getRegion(this);
        if (region != null) {
            if (!RxDataTool.isNullString(region.getName())) {
                locChangeNowCity.setText("当前选择 " + region.getName());
            }
        }
        initRegions();
    }

    private void initRegions() {
        RegionsBean regionsBean = BaseSpUtils.getInstance().getRegionList(this);
        if (regionsBean != null && regionsBean.get_embedded().getContent().size() > 1) {
            adapter_city.setNewData(regionsBean.get_embedded().getContent());
            locRv.addItemDecoration(new TitleItemDecoration(LocActivity.this, regionsBean.get_embedded().getContent()));
            initPermission();
        } else {
            new LocTask(this, o -> {
                if (o != null) {
                    RegionsBean bean = (RegionsBean) o;
                    adapter_city.setNewData(bean.get_embedded().getContent());
                    BaseSpUtils.getInstance().setRegionList(LocActivity.this, bean);
                    locRv.addItemDecoration(new TitleItemDecoration(LocActivity.this, bean.get_embedded().getContent()));
                    initPermission();
                }
            }).execute();
        }
    }

    @Override
    protected void addListener() {

        locChangeBack.setOnClickListener(v -> {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            //隐藏软键盘
            assert imm != null;
            imm.hideSoftInputFromWindow(locChangeEdit.getWindowToken(), 0);
            finish();
        });

        locChangeDelete.setOnClickListener(v -> locChangeEdit.setText(""));

        locChangeNearCity1.setOnClickListener(v -> {
            showChangeDialog(nearCityList.get(0));
        });
        locChangeNearCity2.setOnClickListener(v -> {
            showChangeDialog(nearCityList.get(1));
        });
        locChangeLocCityLl.setOnClickListener(v -> {
            if (isLocSuccess == 0) {
                if (LocContentBean != null) {
                    BaseSpUtils.getInstance().setRegion(LocActivity.this, LocContentBean);
                    setResult(1);
                    finish();
                } else {
                    WpToast.l(LocActivity.this, "失败");
                }
            } else {
                initPermission();
            }
        });
        locChangeEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {
                    locChangeDelete.setVisibility(View.VISIBLE);
                } else {
                    locChangeDelete.setVisibility(View.GONE);
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        locChangeEdit.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                String sContent = locChangeEdit.getText().toString().trim();
                if (!RxDataTool.isNullString(sContent)) {
                    if (null != adapter_city) {
                        int pos = adapter_city.getCityPosition(sContent.replaceAll("\\s*", ""));//记得去除空白字符
                        if (pos != -1) {
                            moveToPosition(pos);
                        } else {
                            WpToast.l(LocActivity.this, "未搜索到该城市,请重新输入");
                        }
                    }
                } else {
                    WpToast.l(LocActivity.this, "请输入城市名称");
                }
            }
            return false;
        });

        locSide.setOnTouchLetterChangeListener(letter -> {
            int pos = adapter_city.getLetterPosition(letter);
            if (pos != -1) {
                locRv.scrollToPosition(pos);
                LinearLayoutManager mLayoutManager =
                        (LinearLayoutManager) locRv.getLayoutManager();
                mLayoutManager.scrollToPositionWithOffset(pos, 0);
            }
        });

        adapter_city.setOnItemClickListener((adapter, view, position) -> showChangeDialog(adapter_city.getData().get(position)));
    }


    private void initPermission() {
        PermissionUtil.handleRunTimePermis(this, () -> beginLocation(), Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION);
    }

    private void beginLocation() {
        LocationManager locationManager = new LocationManager();
        locationManager.getLocation(new LocationManager.GetLocationListener() {
            @Override
            public void OnResult(LocationManager.GetLocationResult result) {
                if (result.mResultId == 0) {
                    isLocSuccess = 0;
                    String city = result.mLocation.mCity;
                    String city_str = city.substring(city.length() - 1);
                    if (city_str.equals("市")) {
                        locChangeLocCity.setText(city.substring(0, (city.length() - 1)));
                    } else {
                        locChangeLocCity.setText(city);
                    }
                    LocActivity.this.findIdByCityCode(city);
                } else {
                    isLocSuccess = 1;
                    locChangeLocCity.setText("定位失败");
                }
            }
        }, this);
    }

    private void showChangeDialog(RegionsBean.EmbeddedBean.ContentBean bean) {
        new MaterialDialog.Builder(this)
                .title("提示")
                .content("是否切换到" + bean.getName() + "?")
                .positiveText("确定")
                .negativeText("取消")
                .negativeColor(ContextCompat.getColor(this,R.color.negative_color))
                .positiveColor(ContextCompat.getColor(this,R.color.positive_color))
                .onPositive((dialog, which) -> {
                    //将城市放入选择历史
                    setNearCityHistory(bean);
                    dialog.dismiss();
                    BaseSpUtils.getInstance().setRegion(LocActivity.this, bean);
                    setResult(1);
                    finish();
                })
                .onNegative((dialog, which) -> dialog.dismiss()).show();
    }


    private void findIdByCityCode(String cityName) {
        RegionsBean regionsBean = BaseSpUtils.getInstance().getRegionList(this);
        for (int i = 0; i < regionsBean.get_embedded().getContent().size(); i++) {
            if (cityName.contains(regionsBean.get_embedded().getContent().get(i).getName())) {
                LocContentBean = regionsBean.get_embedded().getContent().get(i);
                break;
            }
        }
    }


    private void moveToPosition(int n) {
        if (n <= 0) {
            linearLayoutManager.scrollToPositionWithOffset(n, 0);
            linearLayoutManager.setStackFromEnd(true);
        } else {
            final int offset = SHelper.dp2px(this, 24);
            linearLayoutManager.scrollToPositionWithOffset(n, 0);
            linearLayoutManager.setStackFromEnd(true);
            Observable.just("1")
                    .delay(100, TimeUnit.MILLISECONDS)//延时两秒
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<String>() {
                        @Override
                        public void onSubscribe(Disposable d) {
                            addDisposable(d);
                        }

                        @Override
                        public void onNext(String s) {
                            locRv.scrollBy(0, -offset);
                        }

                        @Override
                        public void onError(Throwable e) {
                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        }
    }

    private void addDisposable(Disposable disposable) {
        if (compositeDisposable == null) {
            compositeDisposable = new CompositeDisposable();
        }
        compositeDisposable.add(disposable);
    }

    private void dispose() {
        if (compositeDisposable != null) {
            compositeDisposable.dispose();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dispose();
    }

    public List<RegionsBean.EmbeddedBean.ContentBean> getNearCityHistoryList() {
        List<RegionsBean.EmbeddedBean.ContentBean> list = (List<RegionsBean.EmbeddedBean.ContentBean>) BaseSpUtils.getInstance().getObject(this, "nearCityHistory");
        if (list == null) {
            list = new ArrayList<>();
        }
        return list;
    }

    public void setNearCityHistoryList(List<RegionsBean.EmbeddedBean.ContentBean> list) {
        BaseSpUtils.getInstance().setObject(this, "nearCityHistory", list);
    }

    public void setNearCityHistory(RegionsBean.EmbeddedBean.ContentBean bean) {
        if (bean != null) {
            List<RegionsBean.EmbeddedBean.ContentBean> list = getNearCityHistoryList();
            List<RegionsBean.EmbeddedBean.ContentBean> newList = removeDuplicate(list);
            for (int i = 0; i < newList.size(); i++) {
                if (bean.getCode().equals(newList.get(i).getCode())) {
                    newList.remove(newList.get(i));
                }
            }
            newList.add(0, bean);
            setNearCityHistoryList(newList);
        }
    }

    public static List removeDuplicate(List list) {
        HashSet h = new HashSet(list);
        list.clear();
        list.addAll(h);
        return list;
    }

}
